/**
 * 获取当月日期范围
 * @param {*} s
 */

export function getFirstAndLastMonthDay () {
  let date = []
  let year = new Date().getFullYear()
  let month = new Date().getMonth() + 1
  date[0] = year + '-' + (month < 10 ? '0' + month : month) + '-' + '01'
  let day = new Date(year, month, 0)
  date[1] = year + '-' + (month < 10 ? '0' + month : month) + '-' + day.getDate()
  return date
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export function formatDefaultDate (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 节流
export const throttle = (fn, t) => {
  let prev = Date.now()
  // 下面是一个闭包，可以一直获取到外层的prev变量
  return function () {
    let now = Date.now()
    if (now - prev >= t) {
      fn.apply(this, arguments)
      prev = now
    }
  }
}

// 防抖
export const debounce = (fn, t) => {
  let timer = null
  return function () {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, t)
  }
}
